import { defineStore } from 'pinia';
import { LoginResponse as UserInfo } from "@/api/login/types"

interface State {
  userInfo: UserInfo;
  isLogin: boolean;
}

export const useUserInfoStore = defineStore('userInfo', {
  state: (): State => ({
    userInfo: {
      account: '',
      user_id: '',
      user_type: 0,
      token: '',
    },
    isLogin: false,
  }),
  actions: {
    setUserInfo(data: UserInfo) {
      this.userInfo = data;
      // 在数据发生变化时保存到本地存储
      this.saveState();
    },
    setIsLogin(isLogin: boolean) {
      this.isLogin = isLogin;
      // 在数据发生变化时保存到本地存储
      this.saveState();
    },
    // 新增一个方法用于保存状态到本地存储
    saveState() {
      localStorage.setItem('userInfoState', JSON.stringify(this.$state));
    },
    // 新增一个方法用于从本地存储中恢复状态
    restoreState() {
      const savedState = localStorage.getItem('userInfoState');
      if (savedState) {
        this.$state = JSON.parse(savedState);
      }
    },
  },
});